/*
 * @Author: yangzonglong
 * @Date: 2021-04-01 14:18:21
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-04-20 17:14:14
 * @Auditor: 
 */
import React, { memo, useCallback, useMemo } from 'react';
import { InputNumber } from 'antd';
import { InputNumberProps } from 'antd/lib/input-number';

type Value = string | number | undefined;
interface IProps extends InputNumberProps {
  id?: string;
  onChange?(value: Value, id?: string): void;
}

export const parser = (value: string | undefined) => {
  if (value) return value.replace(/\$\s?|(,*)/g, '');
  return '';
}

const formatter = (value: Value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

export default memo((props: IProps) => {

  const { onChange, id, ...inputNumberProps } = props;

  const _onChange = useCallback((value: Value) => {
    if (!onChange) return;
    if (id) return onChange(value, id);
    onChange(value)
  }, [onChange, id]);

  const handleValue = useMemo(() => {
    const value = inputNumberProps.value;
    if (!value && value !== 0) return;
    if (typeof value === 'number') return value;
    return parseFloat(value)
  }, [inputNumberProps.value]);

  if (inputNumberProps.value && onChange) inputNumberProps.value = handleValue;

  return (
    <InputNumber {...inputNumberProps} parser={parser} formatter={formatter} onChange={_onChange} step={0.01} maxLength={14} min={0}/>
  )
})